<?php

namespace App\Exceptions;

use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Support\Facades\Log;
use PHPOpenSourceSaver\JWTAuth\Exceptions\TokenBlacklistedException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Throwable;
use App\Exceptions\ApiException;
//use Tymon\JWTAuth\Exceptions\TokenBlacklistedException;
//use Tymon\JWTAuth\Exceptions\TokenExpiredException;
//use Tymon\JWTAuth\Exceptions\TokenInvalidException;
class Handler extends ExceptionHandler
{
    /**
     * A list of the exception types that are not reported.
     *
     * @var array<int, class-string<Throwable>>
     */
    protected $dontReport = [
        //
    ];

    /**
     * A list of the inputs that are never flashed for validation exceptions.
     *
     * @var array<int, string>
     */
    protected $dontFlash = [
        'current_password',
        'password',
        'password_confirmation',
    ];

    /**
     * Register the exception handling callbacks for the application.
     *
     * @return void
     */
    public function register()
    {
        $this->reportable(function (Throwable $e) {
            //
        });
    }
    /**
     * 渲染异常为HTTP响应
     *
     * @param \Illuminate\Http\Request $request
     * @param Throwable $exception
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function render($request, Throwable $exception)
    {
        Log::info('Exception type: ' . get_class($exception));
        if ($exception instanceof TokenBlacklistedException ) {

            return response()->json([
                'code' => 401,
                'message' => 'token失效' // 统一提示，避免暴露“blacklisted”
            ], 401);
        }


        if ($exception instanceof NotFoundHttpException) {
            Log::error($exception->getMessage());
            return response([
                'code' => 404,
                'status_code' => -1,
                'message' => '接口请求有误',
            ], 404);
        }
        if ($exception instanceof ServiceException) {
            // 对ServiceException返回统一格式的JSON响应
            $statusCode = $exception->getCode() ?: 400;
            return response()->json([
                'code' => $exception->getCode(),
                'message' => $exception->getMessage(),
                'data' => null
            ], $statusCode);
        }

        if ($exception instanceof \Exception) {
            Log::error($exception->getMessage());
            return response([
                'code' => 500,
                'status_code' => -1,
//                'message' => '请求有误！',
                'message' => $exception->getMessage(),
            ], 500);
        }
        return parent::render($request, $exception);
    }

}
